<template>
  <div class="avatar-uploader">
    <a-upload
      v-model:file-list="fileList"
      name="file"
      list-type="picture-circle"
      class="avatar-uploader"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :customRequest="customUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">上传头像</div>
      </div>
    </a-upload>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { UploadChangeParam, UploadProps } from 'ant-design-vue'
import { uploadAvatarUsingPost } from '../api/userController'

const props = defineProps<{
  value?: string
}>()

const emit = defineEmits(['update:value', 'upload-success'])

const loading = ref<boolean>(false)
const imageUrl = ref<string>('')
const fileList = ref([])

// 监听 value 的变化，更新头像显示
watch(
  () => props.value,
  (newValue) => {
    if (newValue) {
      imageUrl.value = newValue
    }
  },
  { immediate: true }, // 立即执行一次，确保初始值能够显示
)

const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片！')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

const customUpload = async (options: any) => {
  const { file, onSuccess, onError } = options
  loading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await uploadAvatarUsingPost(formData)
    if (res.data.code === 0) {
      imageUrl.value = res.data.data
      emit('update:value', res.data.data)
      emit('upload-success', res.data.data)
      onSuccess()
    } else {
      message.error('上传失败：' + res.data.message)
      onError()
    }
  } catch (error) {
    message.error('上传失败，请重试')
    onError()
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.avatar-uploader {
  text-align: center;
}
.avatar-uploader :deep(.ant-upload) {
  width: 128px;
  height: 128px;
}
.avatar-uploader img {
  width: 128px;
  height: 128px;
  object-fit: cover;
  border-radius: 50%;
}
.ant-upload-text {
  margin-top: 8px;
  font-size: 12px;
}
</style>
